package com.huluobo.a2107monthdemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2107monthdemo.MainActivity
import com.huluobo.a2107monthdemo.R
import com.huluobo.a2107monthdemo.base.BaseMVVMActivity
import com.huluobo.a2107monthdemo.databinding.ActivityLoginBinding
import com.huluobo.a2107monthdemo.db.DatabaseUtil
import com.huluobo.a2107monthdemo.db.Money
import com.huluobo.a2107monthdemo.net.Const
import com.huluobo.a2107monthdemo.register.RegisterActivity

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding>() {
    private lateinit var viewModel: LoginViewModel
    override fun initData() {
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]
        viewModel.loginSuccess.observe(this) {
            if (it.code == 200) {
                SPUtils.getInstance().put(Const.SP_TOKEN, it.data.token)
                DatabaseUtil.getDB().userInfoDao().insertUserInfo(it.data)
                DatabaseUtil.getDB().moneyDao().insertMoney(Money(it.data.id, 10000f))
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                ToastUtils.showLong(it.message)
            }

        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "登录失败:$it")
        }
    }

    override fun initView() {
        dataBinding.loginBtn.setOnClickListener {
            viewModel.login(
                dataBinding.loginUsername.text.toString(),
                dataBinding.loginPassword.text.toString()
            )
        }
        dataBinding.loginToRegister.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_login

}